package com.example.canavar;

import java.util.Timer;
import java.util.TimerTask;
import android.app.ActivityManager;
import android.app.Service;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.IBinder;
import com.example.utils.Utils;

public class TimerService extends Service {
	// constant
	public static final long SEARCH_INTERVAL = 60 * 1000 * 60; // 1 Hour
	final static int RQS_NO_CHANGE = 0;
	final static int RQS_STOP_SERVICE = 1;
	final static int RQS_FREQ_CHANGE = 2;
	final static String RQS = "RQS";
	final static String INTERVAL = "interval";
	final static String ACTION = "NotifyServiceAction";

	// run on another Thread to avoid crash
	private Handler mHandler = new Handler();
	// timer handling
	private Timer mTimer = null;
	private SearchTask mt;
	private NotifyServiceReceiver notifyServiceReceiver;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		Utils.Log("Timer service created");

		// schedule task
		notifyServiceReceiver = new NotifyServiceReceiver();

		super.onCreate();
	}

	public static boolean IsServiceRunning(Context context) {
		ActivityManager manager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (TimerService.class.getName().equals(
					service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Utils.Log("Timer task onStartCommand.");

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ACTION);
		registerReceiver(notifyServiceReceiver, intentFilter);

		resetTimer(intent);

		return super.onStartCommand(intent, flags, startId);
	}

	private void resetTimer(Intent intent) {

		// cancel if already existed
		if (mTimer != null) {
			mTimer.cancel();
		}
		// recreate new
		mTimer = new Timer();

		// Get the search interval value from calling app
		String strInterval = intent.getStringExtra(TimerService.INTERVAL);
		Utils.Log(TimerService.INTERVAL + " value " + strInterval);
		Long longInterval = Long.valueOf(strInterval);

		mTimer.scheduleAtFixedRate(new SearchTaskTimer(), 0, longInterval);
	}

	@Override
	public void onDestroy() {
		Utils.Log("onDestroy called.");
		this.unregisterReceiver(notifyServiceReceiver);
		super.onDestroy();

	}

	class SearchTaskTimer extends TimerTask {

		@Override
		public void run() {

			// skip run if the user is using the activity
			if (MainActivity.active) {
				Utils.Log("Activity is active, TimerTask skipping run()");
				return;
			}

			Utils.Log("Timer task started...");
			// run on another thread
			mHandler.post(new Runnable() {
				@Override
				public void run() {
					Utils.Log("Timer task started, running on a seperate thread.");
					mt = new SearchTask(getApplicationContext());
					mt.execute();
				}

			});
		}
	}

	public class NotifyServiceReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent intent) {
			Utils.Log("ServiceReceiver onReceive called.");
			int rqs = intent.getIntExtra(RQS, 0);
			if (rqs == RQS_STOP_SERVICE) {
				stopSelf();
				mTimer.cancel();
			} else if (rqs == RQS_FREQ_CHANGE) {
				resetTimer(intent);
			}
		}
	}
}